package handler

import (
	amodel "funlog-gserver/model/api"
	model "funlog-gserver/model/db"
	"funlog-gserver/stored/db"
	redis "funlog-gserver/stored/redis"
	"funlog-gserver/utils"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-basic/uuid"
)

//TeamDelHandler  删除团队关系 物理删除
func TeamRelationDelHandler(c *gin.Context) {
	var json amodel.TimeRelationInfo
	err := c.ShouldBindQuery(&json)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	uid, _ := GetUser(c)
	team := model.Team{}
	//根据创建用户id和应用所在团队查询应用信息
	result := db.DB.Where("id= ? and status =1", json.TID).First(&team)
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "团队状态异常", nil)
		return
	}
	//不是自己的团队
	if team.UID != uid {
		SendResponse(c, INADEQUATE_PERMISSIONS, "权限不足", nil)
		return
	}
	//删除团队关系
	result = db.DB.Where("uid = ? and tid = ?", json.UID, json.TID).Unscoped().Delete(&model.TeamRelation{})
	if result.Error != nil {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	} else if result.RowsAffected == 0 {
		SendResponse(c, DB_DELETE_ERROR, "删除失败", nil)
		return
	}
	SendResponse(c, SUCCESS, "ok", nil)
}

//TeamRelationAddHandler 加入团队
func TeamRelationAddHandler(c *gin.Context) {
	var tjson interface{}
	err := c.BindJSON(&tjson)
	json := tjson.(map[string]interface{})
	if err != nil || json["invitationCode"] == nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	invitationCode := utils.Strval(json["invitationCode"])
	tid, err := redis.RDB.Get("team_invitation_" + invitationCode).Result()
	if err != nil || tid == "" {
		SendResponse(c, INVALID_INFORMATION, "邀请码无效", nil)
		return
	}
	uid, user := GetUser(c)
	teamIds := user["teamIds"].([]string)
	team := model.Team{}
	//根据创建用户id和应用所在团队查询应用信息
	result := db.DB.Where("id=? and status =1", tid).First(&team)
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "团队状态异常", nil)
		return
	}
	//自己的团队
	if team.UID == uid {
		SendResponse(c, OPERATION_FAILED, "不能加入自己团队", nil)
		return
	}
	if utils.IsInArray(tid, teamIds) {
		SendResponse(c, OPERATION_FAILED, "已在团队中", nil)
		return
	}
	utid, err := strconv.ParseUint(tid, 10, 32)
	if err != nil {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	}
	teamRelation := model.TeamRelation{TID: uint(utid), UID: uid}
	result = db.DB.Create(&teamRelation)
	if result.Error != nil {
		SendResponse(c, DB_INSERT_ERROR, "加入团队失败", nil)
		return
	}
	redis.RDB.Del("team_invitation_" + invitationCode).Err()
	SendResponse(c, DB_INSERT_ERROR, "加入团队成功", nil)
}

//TeamInvitationHandler 邀请加入团队获取邀请码
func TeamInvitationHandler(c *gin.Context) {
	var tjson interface{}
	err := c.BindJSON(&tjson)
	json := tjson.(map[string]interface{})
	if err != nil || json["tid"] == nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	tid, err := strconv.ParseUint(utils.Strval(json["tid"]), 10, 32)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	team := model.Team{}
	uid, _ := GetUser(c)
	//根据创建用户id和应用所在团队查询应用信息
	result := db.DB.Where("id=? and status =1", tid).First(&team)
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "团队查询失败", nil)
		return
	}
	//如果不是我创建的团队无法邀请
	if team.UID != uid {
		SendResponse(c, INADEQUATE_PERMISSIONS, "权限不足", nil)
		return
	}
	uuid := strings.Replace(uuid.New(), "-", "", -1)
	redis.RDB.Set("team_invitation_"+uuid, tid, time.Hour*24).Err() //邀请码一天内有效
	SendResponse(c, SUCCESS, "ok", map[string]interface{}{"invitationCode": uuid})
}

//TeamRelationGetListHandler 获取某个团队里的所有成员
func TeamRelationGetListHandler(c *gin.Context) {
	tId := c.Param("id")
	if tId == "" || !utils.IsNum(tId) {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	var json amodel.BaseQueryInfo
	err := c.ShouldBindQuery(&json)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	uid, _ := GetUser(c)
	team := model.Team{}
	//查出团队信息
	result := db.DB.Where("status =1 and id = ?", tId).First(&team)
	//查询团队出错
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "查询失败", nil)
		return
	}
	//需要查出的用户表
	var teamUIds []string
	//如果不是本人创建的
	if team.UID != uid {
		teamRelation := &model.TeamRelation{}
		//查询是否在团队里
		userResult := db.DB.Where("uid = ? and tid=?", uid, tId).First(&teamRelation)
		//查不到记录
		if userResult.Error != nil {
			SendResponse(c, DB_QUERY_ERROR, "查询失败", nil)
			return
		}
	} else {
		teamUIds = append(teamUIds, utils.Strval(uid))
	}
	//跳过多少条
	offset := (json.PageNum - 1) * json.Limit
	teamRelations := []model.TeamRelation{}
	//查关系记录
	result = db.DB.Where("tid=?", tId).Limit(json.Limit).Offset(offset).Find(&teamRelations)
	//查询团队出错
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "查询失败", nil)
		return
	}
	for i := 0; i < len(teamRelations); i++ {
		teamUIds = append(teamUIds, utils.Strval(teamRelations[i].UID))
	}
	//返回的 集合
	users := []model.User{}
	//查用户
	result = db.DB.Where("id in ?", teamUIds).Find(&users)
	if result.Error != nil {
		SendResponse(c, DB_QUERY_ERROR, "查询失败", nil)
		return
	}
	SendResponse(c, SUCCESS, "ok", users)

}

//TeamGetListHandler 获取当前用户参与的团队列表
func TeamGetListHandler(c *gin.Context) {
	var json amodel.BaseQueryInfo
	err := c.ShouldBindQuery(&json)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	uid, user := GetUser(c)
	//返回的app 集合
	teams := []model.Team{}
	//跳过多少条
	offset := (json.PageNum - 1) * json.Limit
	//查询应用
	result := db.DB.Where("(uid=? or id in ?) and status =1", uid, user["teamIds"]).Limit(json.Limit).Offset(offset).Find(&teams)
	if result.Error != nil {
		goto SYSERROR
	}
	SendResponse(c, SUCCESS, "ok", teams)
	return
SYSERROR: //系统出错
	SendResponse(c, SYATEM_ERROR, "系统错误", nil)
}

//TeamAddHandler 添加新的团队
func TeamAddHandler(c *gin.Context) {
	var json amodel.TeamInfo
	err := c.ShouldBindBodyWith(&json, binding.JSON)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	uid, _ := GetUser(c)
	team := model.Team{UID: uid, Name: json.Name, Remark: json.Remark}
	// tx := db.DB.Begin()
	result := db.DB.Create(&team)
	if result.Error != nil {
		SendResponse(c, DB_INSERT_ERROR, "系统错误", nil)
	}
	SendResponse(c, SUCCESS, "ok", team)
}

//TeamGetHandler 查询团队
func TeamGetHandler(c *gin.Context) {
	tId := c.Param("id")
	uid, user := GetUser(c)
	teamIds := user["teamIds"]
	team := model.Team{}
	//根据创建用户id和应用所在团队查询应用信息
	result := db.DB.Where("id=? and (uid=? or id in ?) and status =1", tId, uid, teamIds).Find(&team)
	if result.Error != nil {
		goto SYSERROR
	}
	if result.RowsAffected == 0 {
		SendResponse(c, DB_QUERY_ERROR, "查询失败", nil)
	} else {
		SendResponse(c, SUCCESS, "ok", team)
	}
	return
SYSERROR: //系统出错
	SendResponse(c, SYATEM_ERROR, "系统错误", nil)
}

//TeamPutHandler 更新团队信息
func TeamPutHandler(c *gin.Context) {
	var json amodel.TeamInfo
	tid := c.Param("id")
	err := c.ShouldBindBodyWith(&json, binding.JSON)
	if err != nil {
		SendResponse(c, QUERY_PARAMS_ERROR, "参数错误", nil)
		return
	}
	uid, _ := GetUser(c)
	team := model.Team{Name: json.Name, Remark: json.Remark, UID: uid}
	//更新应用
	result := db.DB.Where("uid = ? and id = ?  and status =1", uid, tid).Updates(&team)
	if result.Error != nil {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	} else if result.RowsAffected == 0 {
		SendResponse(c, DB_UPDATE_ERROR, "更新失败", nil)
		return
	}

	SendResponse(c, SUCCESS, "ok", nil)
}

//TeamDelHandler  删除团队，非物理删除，逻辑删除
func TeamDelHandler(c *gin.Context) {
	tid := c.Param("id")
	uid, _ := GetUser(c)
	//更新应用
	result := db.DB.Model(&model.Team{}).Where("uid = ? and id = ?  and status =1", uid, tid).Update("status", 0)
	if result.Error != nil {
		SendResponse(c, SYATEM_ERROR, "系统错误", nil)
		return
	} else if result.RowsAffected == 0 {
		SendResponse(c, DB_DELETE_ERROR, "删除失败", nil)
		return
	}
	SendResponse(c, SUCCESS, "ok", nil)
}
